package com.example.feature.demo.controller;

import com.example.feature.demo.util.FileUtil;
import com.example.feature.demo.util.QRCodeUtils;
import com.example.feature.demo.util.ZipUtils;
import com.zhou.common.exception.CommonException;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletResponse;

/**
 * QRCodeController
 *
 * @author zhouxianfeng
 * @date 2021-7-19
 */
@Slf4j
@Api(value = "云平台二维码接口")
@Controller
@RequestMapping(value = "/qrcode")
public class QRCodeController {

    /**
     * 适用多个二维码打包导出
     *
     * @param resp
     */
    @GetMapping
    public void generatorQrcode(HttpServletResponse resp) {
        String path = "qrcode";
        try {
            QRCodeUtils.encode("test11111", path, "test-filename", true);
            resp.reset();
            resp.setCharacterEncoding("UTF-8");
            resp.setContentType("application/x-msdownload");
            resp.setHeader("Content-Disposition", "attachment; filename=" + "test1111" + ".zip");
            ZipUtils.toZip(path, resp.getOutputStream(), true);
        } catch (Exception e) {
            log.error("生成二维码发生异常！", e);
            throw new CommonException("generate.qrcode.exception");
        } finally {
            FileUtil.deleteAnyone(path);
        }
    }

    /**
     * 单个二维码导出
     *
     * @param resp
     */
    @GetMapping("/generator1")
    public void generatorQrcode1(HttpServletResponse resp) {
        try {
            resp.reset();
            resp.setCharacterEncoding("UTF-8");
            resp.setContentType("application/x-msdownload");
            resp.setHeader("Content-Disposition", "attachment; filename=" + "test1111" + ".jpg");
            QRCodeUtils.encode("test11111", resp.getOutputStream());
        } catch (Exception e) {
            log.error("生成二维码发生异常！", e);
            throw new CommonException("generate.qrcode.exception");
        } finally {
        }
    }
}
